import {objectConvertToQuery} from "../utils/index"
const _baseUrl = () => {
  const {miniProgram: {envVersion}} = wx.getAccountInfoSync()
  const urlObj = {
    //开发
    develop: {
      baseUrl: "http://192.168.1.16:89",
      wsUrl: "ws://192.168.1.16:2346"
    }, 
    //体验
    trial:  {
      baseUrl: "http://sufferer.whmdtechnology.com:9091",
      wsUrl: "ws://sufferer.whmdtechnology.com:2346"
    },
     //线上
    release:  {
      baseUrl: "",
      wsUrl: ""
    },
  }
  if (envVersion === "develop") {
    return urlObj.develop
  }
  return urlObj[envVersion]
}


const {baseUrl,wsUrl} = _baseUrl()

var tokenInvalid = false

const http = ({url = "",method="GET", param = {},toastMsg=true}) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + url ,
      data: param,
      method: method,
      timeout: 20000,
      header: {
        'Authorization': "Bearer " + wx.getStorageSync('token'),
        'Accept': 'application/json; charset=utf-8',
        // "content-type": "application/json、application/x-www-form-urlencoded"
      },
      success: (res) => {
        if (res?.data?.code === 200 && res?.data?.status === "success") {
          resolve(res.data)
        } 
        else {
          if (res?.data?.message == "This action is unauthorized.") {
            if (tokenInvalid) return
            tokenInvalid = true
            let pages = getCurrentPages() //获取加载的页面
            let path = pages[pages.length - 1]
            let url = ''
            let query = ""
            if (path.options) {
              query = objectConvertToQuery(path.options)
            }
            if (query != '') {
              url = `/${path.route}?${query}`
            } else {
              url = `/${path.route}`
            }
            wx.setStorage({
              key: "fromUrl",
              data: url
            })

            wx.showModal({
              title: "登录信息失效，请重新登录！",
              showCancel: false,
              confirmText: "重新登录",
              success() {
                tokenInvalid = false
                wx.removeStorageSync('token')
                wx.removeStorageSync('userInfo')
                wx.reLaunch({
                  url: '/pages/login/index',
                })

              }
            })
            reject(res)
            return
          }
          if (toastMsg && res.data && res.data.message) {
            wx.showModal({
              title: res.data.message,
            })

          }
          reject(res)
        }
      },
      fail: (err) => {
        console.log("fail",err)
        wx.showToast({
          title: '服务异常！',
          icon: "error"
        })
        reject({
          code: 4444,
          data: null,
          message: err.errMsg
        })
      }
    })
  })
}

const get = (url, param = {},config={}) => {
  return http({url,param,...config})
}


const post = (url, param = {},config={}) => {
  return http({url,param,method: 'POST',...config})
}

const put = (url, param = {},config={}) => {
  return http({url,param,method: 'PUT',...config})
}

const del = (url, param = {},config={}) => {
  return http({url,param,method: 'DELETE',...config})
}
module.exports = {
  get,
  post,
  put,
  del,
  baseUrl,
  wsUrl
}